from flask import Blueprint, jsonify, request
from app.models.Skillc2 import RadarChart, User
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
import json
from datetime import datetime

radar_bp = Blueprint('radar', __name__)

@radar_bp.route('/radar/charts', methods=['GET'])
@jwt_required()
def get_radar_charts():
    """获取当前用户的分维雷达图列表"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        charts = RadarChart.query.filter_by(UserId=current_user_id).order_by(RadarChart.CreateTime.desc()).all()
        
        return jsonify({
            'status': 'success',
            'data': [chart.to_dict() for chart in charts]
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@radar_bp.route('/radar/charts/<int:chart_id>', methods=['GET'])
def get_radar_chart(chart_id):
    """获取特定分维雷达图详情"""
    try:
        chart = RadarChart.query.get_or_404(chart_id)
        
        return jsonify({
            'status': 'success',
            'data': chart.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@radar_bp.route('/radar/charts', methods=['POST'])
@jwt_required()
def create_radar_chart():
    """创建分维雷达图"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        data = request.get_json()
        
        # 验证必要字段
        if not data or 'course_scores' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少课程分数数据'
            }), 400
        
        # 验证课程分数格式
        try:
            course_scores = data['course_scores']
            if isinstance(course_scores, str):
                # 如果是字符串，尝试解析为JSON
                json.loads(course_scores)
            elif not isinstance(course_scores, dict):
                return jsonify({
                    'status': 'error',
                    'message': '课程分数格式不正确，应为JSON对象'
                }), 400
                
            # 如果是字典，转换为JSON字符串
            if isinstance(course_scores, dict):
                course_scores = json.dumps(course_scores)
        except json.JSONDecodeError:
            return jsonify({
                'status': 'error',
                'message': '课程分数JSON格式不正确'
            }), 400
        
        chart = RadarChart(
            UserId=current_user_id,
            CourseScores=course_scores
        )
        
        db.session.add(chart)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '分维雷达图创建成功',
            'data': chart.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@radar_bp.route('/radar/charts/<int:chart_id>', methods=['PUT'])
@jwt_required()
def update_radar_chart(chart_id):
    """更新分维雷达图"""
    try:
        current_user_id = int(get_jwt_identity())
        
        chart = RadarChart.query.get_or_404(chart_id)
        
        # 验证是否是雷达图的创建者
        if chart.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以修改雷达图'
            }), 403
            
        data = request.get_json()
        
        # 验证必要字段
        if not data or 'course_scores' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少课程分数数据'
            }), 400
        
        # 验证课程分数格式
        try:
            course_scores = data['course_scores']
            if isinstance(course_scores, str):
                # 如果是字符串，尝试解析为JSON
                json.loads(course_scores)
            elif not isinstance(course_scores, dict):
                return jsonify({
                    'status': 'error',
                    'message': '课程分数格式不正确，应为JSON对象'
                }), 400
                
            # 如果是字典，转换为JSON字符串
            if isinstance(course_scores, dict):
                course_scores = json.dumps(course_scores)
        except json.JSONDecodeError:
            return jsonify({
                'status': 'error',
                'message': '课程分数JSON格式不正确'
            }), 400
        
        chart.CourseScores = course_scores
        chart.UpdateTime = datetime.now()
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '分维雷达图更新成功',
            'data': chart.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@radar_bp.route('/radar/charts/<int:chart_id>', methods=['DELETE'])
@jwt_required()
def delete_radar_chart(chart_id):
    """删除分维雷达图"""
    try:
        current_user_id = int(get_jwt_identity())
        
        chart = RadarChart.query.get_or_404(chart_id)
        
        # 验证是否是雷达图的创建者
        if chart.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以删除雷达图'
            }), 403
            
        db.session.delete(chart)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '分维雷达图删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 